package com.gylang.barcode.domain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.gylang.barcode.enums.Position;
import lombok.Builder;
import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;

/**
 * @author gylang
 * data 2021/6/5
 */
@Data
@Builder(toBuilder = true)
public class BarcodeWrapper {

	private static final Map<EncodeHintType, Object> DEFAULT_HINT_TYPE = CollUtil.newHashMap(3);

	static {
		// 设置二维码字符编码
		DEFAULT_HINT_TYPE.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 设置二维码纠错等级
		DEFAULT_HINT_TYPE.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 设置二维码边距
		DEFAULT_HINT_TYPE.put(EncodeHintType.MARGIN, 0);
		MapUtil.unmodifiable(DEFAULT_HINT_TYPE);
	}


	/** 条形码类型 */
	private BarcodeFormat type;
	/**
	 * @see EncodeHintType
	 */
	Map<EncodeHintType, Object> hintType;


	/** 位置类型 */
	@Builder.Default
	private Position position = Position.CENTER;
	/** x坐标 */
	private int x;
	/** y左边 */
	private int y;

	/**
	 * rgb类型
	 *
	 * @see java.awt.image.BufferedImage
	 */
	@Builder.Default
	private int rgbType = BufferedImage.TYPE_INT_RGB;

	/** 二维码内容 */
	private String content;

	/** 长度 */
	private int boxWith;

	/** 宽度 */
	private int boxHeight;
	/** 内边距 */
	private int boxMargin;

	/** 长度 */
	private int barcodeWith;

	/** 宽度 */
	private int barcodeHeight;

	/** 自定义合成 */
	@Builder.Default
	private Composite composite = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP);

	/** qrcode颜色 */
	@Builder.Default
	private int barOnColor = MatrixToImageConfig.BLACK;

	/** qrcode背景颜色 */
	@Builder.Default
	private int barOffColor = MatrixToImageConfig.WHITE;

	/** qrcode 内边距 */
	private int barcodeMargin;

	/** 背景 不压缩， 直接截切 */
	private String background;


	/** 去掉边缘白边 */
	private boolean removeWhiteEdge;

	/** 文本信息 */
	private List<BarFieldWrapper> textWrappers;

	/** 合成图片 */
	private List<BarFieldWrapper> imgWrappers;


	/** 等比缩放 */
	private boolean scaling;

	public BarcodeWrapper addTextWrappers(BarFieldWrapper wrappers) {
		if (null == textWrappers) {
			textWrappers = CollUtil.newArrayList();
		}
		textWrappers.add(wrappers);
		return this;
	}

	public BarcodeWrapper addImg(BarFieldWrapper wrappers) {
		if (null == imgWrappers) {
			imgWrappers = CollUtil.newArrayList();
		}
		imgWrappers.add(wrappers);
		return this;
	}

	public Map<EncodeHintType, Object> getHintType() {
		if (CollUtil.isEmpty(hintType)) {
			return DEFAULT_HINT_TYPE;
		}
		return hintType;
	}
}
